package com.sibu.yx.promotion.admin.web.support.filter;

import java.io.Serializable;
import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;

import com.doubo.redis.util.RedisTemplateUtil;
import com.sibu.yx.promotion.common.constants.AppConstants;

public class CustomShiroRedisSessionDao extends AbstractSessionDAO {

    private static long expire_second = Duration.ofDays(1).getSeconds();
    private static Map emptyMap = new HashMap(4);

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        ((SimpleSession) session).setId(sessionId);
        RedisTemplateUtil.setObj(getSessionCacheKey(sessionId.toString()), emptyMap, expire_second);
        return sessionId;
    }

    private String getSessionCacheKey(String sessionId) {
        return AppConstants.SESSION_CACHE_KEY + sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        Object o = RedisTemplateUtil.getObj(getSessionCacheKey(sessionId.toString()));
        if (o != null) {
            SimpleSession simpleSession = new SimpleSession();
            simpleSession.setId(sessionId);
            simpleSession.setAttributes((Map<Object, Object>) o);
            return simpleSession;
        }
        return null;
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        Object o = ((SimpleSession) session).getAttributes();
        RedisTemplateUtil.setObj(getSessionCacheKey(session.getId().toString()), o == null ? emptyMap : o, expire_second);
    }

    @Override
    public void delete(Session session) {
        RedisTemplateUtil.del(getSessionCacheKey(session.getId().toString()));
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return Collections.emptyList();
    }
}
